<template>
    <div>
        <el-table ref="tableRef" v-loading="loading" :data="lists" @selection-change="handleSelectionChange" :row-key="getRowKey" @clearSelection="clear_selection">
            <el-table-column v-if="showCheck" type="selection" align='center' width="60" :reserve-selection="true"></el-table-column>
            <el-table-column v-if="sequence && page" type="index" label="序号" width="60" align='center'>
                <template #default="scope">
                    <span>{{scope.$index+(page.pageIndex - 1) * page.pageSize + 1}} </span>
                </template>
            </el-table-column>
            <slot/>
        </el-table> 
        <div class="gva-pagination my-pagination" v-if="page">
            <el-pagination
              :current-page="page.pageIndex"
              :page-size="page.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="page.total"
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            />
        </div>   
    </div>        
</template>

<script setup>
    import { defineProps,ref,defineEmits,defineExpose } from 'vue';
    const props = defineProps({
        lists:Array,
        page:{}, // 分页：{pageSize,pageIndex,total}
        loading:{
            type:Boolean,
            default:()=>false
        },
        showCheck:{  // 是否显示选择框
           type:Boolean,
           default:false 
        },
        sequence:{  // 是否显示序列号
           type:Boolean,
           default:true 
        },
        selectKey:{  // 当表格需要选择时，选择后获取的关键字段
           type:String,
           default:'all'  // 默认把当前选择的整个数据对象保存
        },
        rowKey:String // 行数据的 Key，用来优化 Table 的渲染,reserve-selection为true时，必填 (最后是记录的唯一标识)
    })
    const emit = defineEmits(['selectionChange','handleCurrentChange'])

    const tableRef = ref(null)
    const multipleSelectionIds = ref([])

    const handleSelectionChange = (items)=>{
        if(props.selectKey=='all'){
            emit('selection-change',items)
            return
        }
        multipleSelectionIds.value = []
        for(let i=0;i<items.length;i++){
            multipleSelectionIds.value.push(items[i][props.selectKey])
        }
        emit('selection-change',multipleSelectionIds.value)
    }
    const handleCurrentChange = (pageIndex)=> {
        emit('current-change',pageIndex)
    }
    const handleSizeChange = (pageSize)=>{
        emit('size-change',pageSize)
    }
    const getRowKey = (row)=>{
        return row[props.rowKey]
    }
    // 清空用户所选
    const clear_selection = ()=>{
        tableRef.value.clearSelection()
    }
    defineExpose({clear_selection})

</script>

<style lang="scss">
.my-pagination {
    .el-input__suffix{
        margin-top: 0!important;
    }
}
</style>